import { createSlice } from "@reduxjs/toolkit";
import { setToken, getToken, removeToken } from "@/utils/index";
import { loginAPI, getProfileAPI } from "@/apis/user";


const userStore = createSlice({
    name: "user",
    initialState: {
        token: getToken() ?? "",
        userInfo: {}
    },
    // 同步修改方法
    reducers: {
        setAsyncToken(state, action) {
            state.token = action.payload

            // 存储token到localStorage 数据持久化
            setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            state.userInfo = {}
            state.token = ""
            removeToken()
        }
    }
})
// 解构出actionCreater函数
const { setAsyncToken, setUserInfo, clearUserInfo } = userStore.actions

// 获取reducer函数
const reducer = userStore.reducer

// 异步方法，完成登录获取token
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await loginAPI(loginForm)
        // 提交同步action进行token的保存
        dispatch(setAsyncToken(res.data.token))
    }
}

// 异步方法，获取个人用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getProfileAPI()
        dispatch(setUserInfo(res.data))
    }
}

export { fetchLogin, fetchUserInfo, setAsyncToken, clearUserInfo }
export default reducer